package com.qianfeng.project.model.webservice;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import android.util.Log;

public class WebApiProvider {
	private static final AsyncHttpClient httpClient = new AsyncHttpClient();
	// 连网最大重试次数和超时
	private static final int MAXRETRIES = 3;
	private static final int TIMEOUT = 10000;

	// 单例模式
	static {
		// setmaxretriesandtimeout集之间的重试的最大重试次数和超时
		// setTimeout设置连接/套接字超时-这是一个默认的10
		httpClient.setMaxRetriesAndTimeout(MAXRETRIES, TIMEOUT);
	}

	private static AsyncHttpClient getHttpClient() {
		return httpClient;
	}

	// Request.Params是所有post和get传过来的值的集合,
	private static RequestParams getParams() {
		final RequestParams params = new RequestParams();
		return params;
	}

	// GET请求
	protected static final void getRequest(final Object requestObj, final String url,
			final AsyncHttpResponseHandler resp) {
		RequestParams params = getParams();
		setParam(requestObj, params);

	}

	protected static final void getRequest(String url, final AsyncHttpResponseHandler resp) {
		AsyncHttpClient httpClient = getHttpClient();
		if (httpClient != null) {
			Log.v("TAG", "url===" + url);
			httpClient.get(url, resp);
		}
	}

	// post
	protected static final void postRequest(final Object requestObj, final String url,
			final AsyncHttpResponseHandler resp) {
		RequestParams params = getParams();
		setParam(requestObj, params);
		AsyncHttpClient httpClient = getHttpClient();
		if (httpClient != null) {
			httpClient.post(url, params, resp);
		}
	}

	private static void setParam(final Object requestObj, final RequestParams params) {
		if (requestObj != null) {
			final Class clazz = requestObj.getClass();
			if (clazz != null) {
				reflect(clazz, params, requestObj);
			}
		}
	}

	private static final void reflect(final Class clazz, final RequestParams params, final Object requestObj) {
		if (clazz == null || params == null)
			return;
		Field[] fields = clazz.getDeclaredFields();
		for (int j = 0; j < fields.length; j++) {
			fields[j].setAccessible(true);
			if (isList(fields[j])) {
				continue;
			}
			try {
				params.put(fields[j].getName(), fields[j].get(requestObj));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		Class superclass = clazz.getSuperclass();
		if (superclass != null) {
			reflect(superclass, params, requestObj);
		}
	}

	private static final boolean isList(final Field field) {
		if (field != null) {
			String name = field.getType().getName();
			String List = List.class.getName();
			String ArrayList = ArrayList.class.getName();
			return ArrayList.equals(name) || List.equals(name);
		}
		return false;
	}
}
